package com.huazai.juc.core;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * 来总结一下怎么写生产者和消费者模式吧：
 * 首先要来获得ReentrantLock这个锁，然后通过lock来获得到Condition
 * 然后使用try catch finally 结构来进行代码设计
 * 首先先lock.lock()获取到当亲的锁，再到finally里面lock.unlock()，释放掉锁。
 *
 */
public class ShareData {
    private int number = 0;
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    public void increment() {
        // 同步代码块，加锁
        lock.lock();

        try {
            // 判断 防止虚假唤醒
            while (number != 0) {
                // 等待不能生产
                condition.await();
            }
            // 干活
            number ++;
            System.out.println(Thread.currentThread().getName() + "  " + number);
            // 通知 唤醒
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() throws Exception {
        // 同步代码块，加锁
        lock.lock();
        try {
            while (number == 0) {
                // 等待不能消费
                condition.await();
            }
            // 干活
            number --;
            System.out.println(Thread.currentThread().getName() + "  " + number);
            // 通知 唤醒
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
